(function(global) {
    const serverUrl = 'http://127.0.0.1:2080/api'


    var loadTemplate = function(name) {
        id = name + "_tmpl";
        return document.getElementById(id).innerHTML;
    }

    const pad = (num, n) => (Array(n).join(0) + num).slice(-n)

    const convertDuration = duration => {
        const h = Math.floor(duration / 3600)
        const m = Math.floor(duration % 3600 / 60)
        const s = Math.floor(duration % 60)
        return h ? `${pad(h, 2)}:${pad(m, 2)}:${pad(s, 2)}` : `${pad(m, 2)}:${pad(s, 2)}`
    }

    const audio = new Audio()


    /////////////////////////////////

    const Foo = { template: '<div>foo</div>' }
    const Bar = { template: '<div>bar</div>' }
    const Baz = { template: '<div>baz</div>' }
    const Demo = { template: '<div>demo</div>' }

    var Home = {
        template: loadTemplate('home'),
    }


    var Songs = {
        template: loadTemplate('list'),
        data: function() {
            this.$http.jsonp(`${serverUrl}/demo`)
                .then(res => {
                    console.log(res.data)

                    this.list = res.data
                })
            return { list: [] }
        },
        methods: {
            pad: pad,
            convert: convertDuration,
        }
    }

    var Player = {
        template: loadTemplate('player'),
        data: function() {
            return {
                loading: false,
                error: null,
                player: null,
            }
        },
        created() {
            this.fetchData()
        },
        watch: {
            // 如果路由有变化，会再次执行该方法
            '$route': 'fetchData'
        },
        methods: {
            convert: convertDuration,
            fetchData() {
                this.error = this.player = null
                this.loading = true

                this.getMusic(this.$route.params.id);

            },
            getMusic(id) {

                this.$http.jsonp(`${serverUrl}/demo/${id}`).then(res => {
                    if (!res.ok) {
                        this.loading = false
                        this.error = '网络请求失败'

                    } else {
                        let player = { current: 0, playing: false, random: false }
                        Object.assign(player, res.data)
                        console.log(player);
                        this.loading = false
                        this.error = null
                        this.player = player
                        this.setAudio(player)
                    }

                }).catch(function(error) {
                    this.loading = false
                    this.error = error
                })

            },

            setAudio(player) {
                audio.src = player.music
                audio.autoplay = true
                audio.addEventListener('loadedmetadata', () => {
                    player.duration = audio.duration
                })
                audio.addEventListener('timeupdate', () => {
                    player.current = audio.currentTime
                })
                audio.addEventListener('play', () => {
                    player.playing = true
                })
                audio.addEventListener('pause', () => {
                    player.playing = false
                })

            },
            play() {
                if (this.player.playing) {
                    audio.pause()
                } else {
                    audio.play()
                }
                this.player.playing = !this.player.playing
            },
            progress() {
                audio.currentTime = this.player.current
            },
            next() {
                this.$http.jsonp(`${serverUrl}/demo`).then(res => {
                    const ids = res.data.map(s => s.id)
                    let targetIndex = ids.indexOf(this.player.id) + 1
                    if (targetIndex >= ids.length) {
                        targetIndex = 0
                    }
                    router.go({ name: 'player', params: { id: ids[targetIndex] } })
                })
            },
            prev() {
                this.$http.jsonp(`${serverUrl}/demo`).then(res => {
                    const ids = res.data.map(s => s.id)
                    let targetIndex = ids.indexOf(this.player.id) - 1
                    if (targetIndex < 0) {
                        targetIndex = ids.length - 1
                    }
                    router.go({ name: 'player', params: { id: ids[targetIndex] } })
                })
            }
        }
    }


    var routes = [{
            path: '/',
            redirect: '/home'
        },
        {
            name: 'home',
            path: '/home',
            //component: Home,
            components: {
                default: Home,
                a: Bar,
                b: Baz,
                c: Demo
            }
        },
        {
            name: 'songs',
            path: '/songs',
            component: Songs,
        },
        {
            name: 'player',
            path: '/songs/:id',
            component: Player,
        }
    ]

    var router = new global.VueRouter({
        routes
    })

    const app = new global.Vue({
        router
    }).$mount('#app')



})(this)